package come.bjpowernode.javase.exam4;
/*
//面试题;
    doOther()在执行的时候需要等待doSome()方法的结束吗？
    需要:因为静态方法是类锁，不管创建了几个对象类锁只有一把。

 */
public class Exam01 {
    public static void main(String[] args) {

        MyClass mc = new MyClass();
        MyClass mc2 = new MyClass();

        Thread t1 = new MyThread(mc);
        Thread t2 = new MyThread(mc2);
        t1.setName("t1");
        t2.setName("t2");

        t1.start();
        try {
            //这个睡眠的作用是为了保证t1线执行
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}

class MyThread extends Thread{
    private MyClass mc;
    public MyThread(MyClass mc){
        this.mc = mc;
    }
    public void run(){
        if(Thread.currentThread().getName().equals("t1")){
            mc.doSome();
        }
        if(Thread.currentThread().getName().equals("t2")){
            mc.doOther();
        }
    }
}

class MyClass{

    //synchronize出现在静态方法上是类锁
    public synchronized static void doSome(){
        System.out.println("doSome begin!");
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("doSome over!");
    }

    //synchronize出现在实例方法上表示锁this
    public synchronized static void doOther(){
        System.out.println("doOther begin");
        System.out.println("doOther over");

    }
}
